package cn.com.dealme.nutz.hibernate.transaction;

import org.hibernate.Session;
import org.nutz.aop.InterceptorChain;
import org.nutz.aop.interceptor.AbstractMethodInterceptor;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class TransactionInterceptor extends AbstractMethodInterceptor {
	
	private static final Log log = Logs.getLog(TransactionInterceptor.class);
	
	private Session session;
	
	public TransactionInterceptor() {
	}

	@Override
	public void filter(InterceptorChain chain) throws Throwable {
		try {
			session.beginTransaction();
			if(log.isDebugEnabled()) {
				log.debug("session.beginTransaction()");
			}
			chain.doChain();
			session.getTransaction().commit();
			if(log.isDebugEnabled()) {
				log.debug("session.getTransaction().commit()");
			}
			session = null;
		} catch (Exception e) {
			session.getTransaction().rollback();
			if(log.isDebugEnabled()) {
				log.debug("session.getTransaction().rollback() because: " + e.getMessage());
			}
			session = null;
			throw e;
		}
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	
}
